/*
	Copyright (c) 2006-2008, Grant Jones <grant@gxjones.com>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or
	without modification, are permitted provided that the following
	conditions are met:

		Redistributions of source code must retain the above copyright
		notice, this list of conditions and the following disclaimer.
		
		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in
		the documentation and/or other materials provided with the
		distribution.
		
		Neither the name of the gxjones.com nor the names of its
		contributors may be used to endorse or promote products derived
		from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
	
	http://www.opensource.org/licenses/bsd-license.php
*/

//
//  EAGLView.m
//  Mote-M BaseCode
//
//  Created by Grant Jones on 7/22/08.
//



#import <QuartzCore/QuartzCore.h>
#import <OpenGLES/EAGLDrawable.h>

#import "EAGLView.h"

#define USE_DEPTH_BUFFER 1

// Error w/ ad hoc installation via iTunes:
// http://discussions.apple.com/thread.jspa?threadID=1601268

#include <sys/time.h>

double getMSCount(void)
{
	struct timeval t;
	gettimeofday(&t, NULL);
	return ((double)t.tv_sec * 1000000.0 + (double)t.tv_usec) / 1000.0;
} 



// A class extension to declare private methods
@interface EAGLView ()

@property (nonatomic, retain) EAGLContext *context;
@property (nonatomic, assign) NSTimer *animationTimer;

- (BOOL) createFramebuffer;
- (void) destroyFramebuffer;

@end


@implementation EAGLView
//@synthesize miscView;

@synthesize context;
@synthesize animationTimer;
@synthesize animationInterval;
@synthesize gamePaused;

@synthesize dataSource;
@synthesize delegate;

@synthesize rootGLView=_root_view;

// You must implement this
+ (Class)layerClass {
	return [CAEAGLLayer class];
}


//The GL view is stored in the nib file. When it's unarchived it's sent -initWithCoder:
- (id)initWithCoder:(NSCoder*)coder {

	if ((self = [super initWithCoder:coder])) {
		// Get the layer
		CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
		
		eaglLayer.opaque = YES;
		eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
		   [NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking,
		   kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
		
		context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
		
		if (!context || ![EAGLContext setCurrentContext:context]  || ![self createFramebuffer]) {
			[self release];
			return nil;
		}

		
		animationInterval = 1.0 / 60.0;

		
		_last_t = getMSCount();
		[self setupView];
	}
	return self;
}

- (void)setupView {
#if TARGET_IPHONE_SIMULATOR
	NSLog(@"setupView: %d, %d", backingWidth, backingHeight );
#endif	
	glViewport(0, 0, backingWidth, backingHeight);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrthof(0.0f, backingWidth, 0, backingHeight, 0.0f, 1.0f);	
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	
	glEnable(GL_TEXTURE_2D);

	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);	
	
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	
	
	_root_view = [[BaseGLView alloc] init];
	_root_view.backingWidth = backingWidth;
	_root_view.backingHeight = backingHeight;

}

- (void)drawView {
	[EAGLContext setCurrentContext:context];
	
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);

	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	glColor4f( 1,1,1,1 );
	
	[_root_view drawView];	// calls draw on self and all subviews
		
	glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
	[context presentRenderbuffer:GL_RENDERBUFFER_OES];

	double cur_t = getMSCount();
	double delta_t = cur_t - _last_t;
	_last_t = cur_t;

	delta_t -= _timeout_t;	/* take calc time off clock */
	_timeout_t = 0;
	if( !gamePaused && self.dataSource) {
		[self.dataSource tickWithDelta:delta_t];
	}

	[_root_view tickWithDelta:delta_t];
}


#pragma mark Handling OpenGL and UIView switching
- (void)makeOpenGLVisible {

	[self startAnimation];

}

- (void)switchToUIView:(UIView *)view {
	[self stopAnimation];

	UIView *super_view = [self superview];
	[self removeFromSuperview];
	[super_view addSubview:view];	
/*	[view makeViewVisibleWhenDone:self];*/
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	double start_time, end_time;

	if( _gameOver_block_input )
		return;
		
	start_time = getMSCount();

	[_root_view touchesBegan:touches withEvent:event];

	end_time = getMSCount();
#if TARGET_IPHONE_SIMULATOR	
//	NSLog(@"touchesBegan took: %f", (end_time-start_time) );
#endif	
	_timeout_t += (end_time-start_time);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	double start_time, end_time;

	
	if( _gameOver_block_input )
		return;
	
	start_time = getMSCount();
	
	[_root_view touchesMoved:touches withEvent:event];
	
	end_time = getMSCount();
	
	_timeout_t += (end_time-start_time);		
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	double start_time, end_time;

	if( _gameOver_block_input )
		return;
	
	start_time = getMSCount();

	[_root_view touchesEnded:touches withEvent:event];
	
	end_time = getMSCount();
	
	_timeout_t += (end_time-start_time);		
	
}

- (void) purgeTextureCaches {
	[_root_view purgeTextureCaches];
}

- (void)layoutSubviews {
	[EAGLContext setCurrentContext:context];
	[self destroyFramebuffer];
	[self createFramebuffer];
	[self drawView];
}


- (BOOL)createFramebuffer {
	
	glGenFramebuffersOES(1, &viewFramebuffer);
	glGenRenderbuffersOES(1, &viewRenderbuffer);
	
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
	glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
	[context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
	glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
	
	glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
	glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
	
	if (USE_DEPTH_BUFFER) {
		glGenRenderbuffersOES(1, &depthRenderbuffer);
		glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
		glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
		glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
	}

	if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
		NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
		return NO;
	}
	
	return YES;
}


- (void)destroyFramebuffer {
	
	glDeleteFramebuffersOES(1, &viewFramebuffer);
	viewFramebuffer = 0;
	glDeleteRenderbuffersOES(1, &viewRenderbuffer);
	viewRenderbuffer = 0;
	
	if(depthRenderbuffer) {
		glDeleteRenderbuffersOES(1, &depthRenderbuffer);
		depthRenderbuffer = 0;
	}
}


- (void)startAnimation {
	[self.delegate EAGLViewBeginsAnimation:self];
	
	_last_t = getMSCount();	/* the "pause" never happened */
	
	self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(drawView) userInfo:nil repeats:YES];
}


- (void)stopAnimation {
	[self.delegate EAGLViewStopsAnimation:self];

	self.animationTimer = nil;
}


- (void)setAnimationTimer:(NSTimer *)newTimer {
	[animationTimer invalidate];
	animationTimer = newTimer;
}


- (void)setAnimationInterval:(NSTimeInterval)interval {
	
	animationInterval = interval;
	if (animationTimer) {
		[self stopAnimation];
		[self startAnimation];
	}
}


- (void)dealloc {
	
	[self stopAnimation];
	
	if ([EAGLContext currentContext] == context) {
		[EAGLContext setCurrentContext:nil];
	}
	
	[context release];	
	
	[super dealloc];
}

@end
